package com.pay.service;

import com.pay.common.util.DateFormatUtil;
import com.pay.common.util.GsonUtils;
import com.pay.dao.entity.UserInfo;
import com.pay.dao.entity.UserInfoExample;
import com.pay.dao.mapper.UserInfoMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@Service
public class TokenUntil {

    @Autowired
    private UserInfoMapper userInfoMapper;

    /**
     * 根据token获取user
     * @return
     */
    public UserInfo getUserbyToken(HttpServletRequest arg0){
        String token = getRequest().getHeader("token");
        if(StringUtils.isBlank(token)){
            return null;
        }
        UserInfoExample userInfoExample = new UserInfoExample();
        userInfoExample.createCriteria().andYl1EqualTo(token).andUpdatedDateGreaterThan(DateFormatUtil.getOneHouser());
        List<UserInfo> userInfoList = userInfoMapper.selectByExample(userInfoExample);
        if(userInfoList==null||userInfoList.size()<=0){
            return null;
        }
        UserInfo userInfo= userInfoList.get(0);
        userInfo.setUpdatedDate(new Date());
        userInfoMapper.updateByPrimaryKey(userInfo);
        return userInfoList.get(0);
    }



    /**
     * 获取当前的request
     * @return
     */
    public HttpServletRequest getRequest() {
        ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return attrs.getRequest();
    }
}
